package com.yx.china.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.yx.china.project.entities.Payment;
import com.yx.china.project.entities.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
@RestController
@Slf4j
public class ConsumerController {
    @Resource
    private RestTemplate restTemplate;
    @GetMapping("/consumer/pay/{id}")
    //@SentinelResource(value = "abc") 无配置,运行异常直接报到页面
    //@SentinelResource(value = "abc",fallback = "handlerFallback")配置fallback,出错直接走对应的方法
    //@SentinelResource(value = "abc",blockHandler = "blockHandler") // 配置了blockHandler，只负责sentinel控制台配置违规,到达规则才走对应的方法
    @SentinelResource(value = "fallback",fallback = "handlerFallback", blockHandler = "blockHandler",
            exceptionsToIgnore = {IllegalArgumentException.class}) // 配置了blockHandler和fallback 达到那个标准就走那个方法,exceptionsToIgnore排除异常,就是有异常也不走对应的方法
    public ResponseResult<Payment> paymentSQL(@PathVariable("id") Integer id){
        ResponseResult<Payment> result = restTemplate.getForObject("http://cloudalibaba-pay-service" + "/pay/" + id, ResponseResult.class);
        if(id == 4){
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
        }else if(result.getResData() == null){
            throw new NullPointerException("NullPointerException,该ID没有记录，空指针异常");
        }
        return result;
    }
    // 本例是fallback
    public ResponseResult handlerFallback(@PathVariable("id") Integer id, Throwable e){
        return new ResponseResult(444, "兜底异常handler，exception内容"+e.getMessage(), id);
    }
    // 本例是blockHandler
    public ResponseResult blockHandler(@PathVariable("id") Integer id, BlockException exception){
        return new ResponseResult<>(445, "blockHandler-sentinel 限流，无此流水号：blockException" + exception.getMessage(), id);
    }
}
